<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="search-container">
        <el-input
          v-model="listQuery.name"
          placeholder="名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.ip"
          placeholder="IP"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.channel"
          placeholder="通道号"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button
          class="filter-item"
          type="primary"
          @click="handleFilter"
        >
          {{ $t("table.search") }}
        </el-button>
      </div>
      <el-button
        v-if="Number(type) === 1"
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 + 1 * (listQuery.current - 1) * listQuery.size }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="名称">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column width="180px" align="center" label="ip">
        <template slot-scope="scope">
          <span>{{ scope.row.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column width="180px" align="center" label="通道">
        <template slot-scope="scope">
          <span>{{ getChanelLabel(scope.row.channel) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="类型">
        <template slot-scope="scope">
          <span>{{ scope.row.channelFlag === 1 ? '上班打卡' : '通道打卡' }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.onlineStatus ? 1 : 2 | statusFilter">
            {{ scope.row.onlineStatus ? "在线" : "离线" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="180px" label="创建日期">
        <template slot-scope="scope">
          <span> {{ scope.row.createTime }}</span>
          <!-- <span> {{ new Date(scope.row.createTime) | parseTime("{y}-{m}-{d} {h}:{i}") }}</span> -->
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" :width="Number(type) === 1 ? 240 : 120">
        <template slot-scope="scope">
          <el-popconfirm v-if="Number(type) === 1" title="确认同步吗？" @onConfirm="onSync(scope.row.id)">
            <el-button
              slot="reference"
              type="success"
              size="small"
              style="margin-right: 10px"
            >
              同步
            </el-button>
          </el-popconfirm>
          <!-- <el-button
            slot="reference"
            type="primary"
            style="margin-right: 10px"
            size="small"
            @click="onIssue(scope.row.id)"
          >
            下发
          </el-button> -->
          <el-popconfirm v-if="Number(type) === 1" title="确认一键下发吗？" @onConfirm="onAllIssue(scope.row.id)">
            <el-button
              slot="reference"
              type="success"
              size="small"
              style="margin-right: 10px"
            >
              一键下发
            </el-button>
          </el-popconfirm>
          <router-link :to="'/device/edit/' + scope.row.id">
            <el-button type="primary" size="small"> 查看 </el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" width="320px" :visible.sync="dialogVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="90px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="ip" prop="ip">
          <el-input v-model="temp.ip" />
        </el-form-item>
        <el-form-item label="通道标识" prop="channelFlag">
          <el-select
            v-model="temp.channelFlag"
            class="filter-item"
            placeholder="请选择标识"
          >
            <el-option
              v-for="item in channelTypes"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通道" prop="channel">
          <el-select
            v-model="temp.channel"
            class="filter-item"
            placeholder="请选择通道"
          >
            <el-option
              v-for="item in channels"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="下发" width="440px" :visible.sync="issueVisible">
      <div class="face-container">
        <div
          v-for="item in memberList"
          :key="item.id"
          class="box-container"
          @click="onChange(item.uid)"
        >
          <el-avatar shape="square" :size="76" fit="cover" :src="item.faceImg">
            <img src="@/assets/error.png">
          </el-avatar>
          <div class="text-container">
            <div>{{ item.name }}</div>
            <div>{{ item.uid }}</div>
          </div>

          <div class="check-box">
            <el-checkbox
              :value="actions.includes(item.uid)"
              style="pointer-events: none"
            />
          </div>
        </div>
      </div>

      <pagination
        v-show="memberTotal > 0"
        :total="memberTotal"
        :page.sync="memberQuery.current"
        :limit.sync="memberQuery.size"
        style="padding: 0"
        @pagination="fetchList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="issueVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="onSave"
        >
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addDevice, deviceList, syncDevice, syncUsetToDevice, syncAllUserInfo } from '@/api/device'
import { fetchList } from '@/api/member'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import channels from './components/mixins/channels'

export default {
  name: 'ArticleList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  mixins: [channels],
  data() {
    const validateRequire = (rule, value, callback) => {
      const ipRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
      if (value === '') {
        this.$message({
          message: rule.field + '不能为空',
          type: 'error'
        })
        callback(new Error(rule.field + '不能为空'))
      } else if (!ipRegex.test(value)) {
        this.$message({
          message: '请输入正确的ip地址',
          type: 'error'
        })
        callback(new Error('请输入正确的ip地址'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        current: 1,
        size: 10,
        name: '',
        ip: '',
        channel: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogVisible: false,
      channelTypes: [
        {
          key: 1,
          label: '上班打卡'
        },
        {
          key: 2,
          label: '通道打卡'
        }
      ],
      temp: {
        id: undefined,
        name: '',
        ip: '',
        channel: '',
        channelFlag: 1
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        ip: [{ required: true, validator: validateRequire, trigger: 'blur' }],
        channelFlag: [
          { required: true, message: '通道标识是必填项', trigger: 'change' }
        ],
        channel: [
          { required: true, message: '通道号不能为空', trigger: 'blur' }
        ]
      },
      issueVisible: false,
      memberList: [],
      memberTotal: 0,
      memberQuery: {
        current: 1,
        size: 10
      },
      actions: [],
      deviceId: '',
      asyncs: []
    }
  },
  computed: {
    ...mapGetters([
      'type'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      deviceList(this.listQuery).then((response) => {
        const { records, total } = response.object
        this.list = records || []
        this.total = total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        ip: '',
        channel: '',
        channelFlag: 1
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          addDevice(this.temp).then(() => {
            this.handleFilter()
            this.dialogVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // const tempData = Object.assign({}, this.temp)
          // updateArticle(tempData).then(() => {
          //   const index = this.list.findIndex(v => v.id === this.temp.id)
          //   this.list.splice(index, 1, this.temp)
          //   this.dialogFormVisible = false
          //   this.$notify({
          //     title: '成功',
          //     message: '更新成功',
          //     type: 'success',
          //     duration: 2000
          //   })
          // })
        }
      })
    },
    onSync(id) {
      const formData = new FormData()
      formData.append('deviceId', id)
      syncDevice(formData).then(() => {
        this.$notify({
          title: '成功',
          message: '同步成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    onAllIssue(id) {
      if (this.asyncs.includes(id)) {
        return this.$message.warning('10s内不可重复点击!')
      }
      this.asyncs.push(id)
      setTimeout(() => {
        this.asyncs = this.asyncs.filter(r => r !== id)
      }, 10000)
      const formData = new FormData()
      formData.append('deviceId', id)
      syncAllUserInfo(formData).then(() => {
        this.$notify({
          title: '成功',
          message: '一键下发成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    fetchList() {
      fetchList(this.memberQuery).then((response) => {
        const { records, total } = response.object
        this.memberList = records || []
        this.memberTotal = total
      })
    },
    onIssue(id) {
      this.deviceId = id
      this.issueVisible = true
      this.fetchList()
    },
    onChange(id) {
      const index = this.actions.indexOf(id)
      if (index > -1) {
        this.actions.splice(index, 1)
        return
      }
      if (this.actions.length > 5) {
        return this.$message.error('最多选择6个')
      }
      this.actions.push(id)
    },
    onSave() {
      if (this.actions.length === 0) {
        return this.$message.error('请选择人脸')
      }
      const formData = new FormData()
      formData.append('deviceId', this.deviceId)
      formData.append('uids', this.actions)
      syncUsetToDevice(formData).then(() => {
        this.issueVisible = false
        this.$notify({
          title: '成功',
          message: '下发成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    getChanelLabel(key) {
      const channel = this.channels.filter(r => r.key === key)[0]
      return channel ? channel.label : '---'
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.face-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.box-container {
  position: relative;
  width: 76px;
  height: 76px;
  border-radius: 5px;
  overflow: hidden;
  background: #f5f5f5;
  cursor: pointer;
}
img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.check-box {
  position: absolute;
  top: 4px;
  right: 4px;
}
.text-container {
  position: absolute;
  bottom: 0px;
  left: 0;
  width: 100%;
  padding: 4px 0;
  text-align: center;
  background: rgba(0, 0, 0, 0.1);
  color: #fff;
  backdrop-filter: blur(6px);
}
</style>
